package config

import (
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin"
)

//初始化session操作
func Session() gin.HandlerFunc {
	redisConfig := Config.Section("redis")
	host, err := redisConfig.GetKey("Host")
	if err != nil {
		panic(err.Error())
	}
	passwd, err := redisConfig.GetKey("Password")
	if err != nil {
		panic(err.Error())
	}
	store, err := redis.NewStore(10, "tcp", fmt.Sprintf("%s", host), fmt.Sprintf("%s", passwd), []byte("secret"))
	if err != nil {
		panic(err.Error())
	}

	return sessions.Sessions("mysession", store)

}

// set操作
func SetSess(context *gin.Context, key interface{}, value interface{}) error {
	session := sessions.Default(context)
	if session == nil {
		return nil
	}
	session.Set(key, value)
	return session.Save()
}

// get操作
func GetSess(context *gin.Context, key interface{}) interface{} {
	session := sessions.Default(context)
	return session.Get(key)
}
